package 同步辅助类;

import java.util.concurrent.CyclicBarrier;
/*
所有线程等待全部线程到达栅栏后才进行下一步操作，最后到达的线程会完成run任务
 */
public class CyclicBarrierDemo {


    static class Task extends Thread {

        int id;
        CyclicBarrier cyclicBarrier;

        public Task(int id,CyclicBarrier cyclicBarrier) {
            this.id=id;
            this.cyclicBarrier = cyclicBarrier;
        }

        public void run() {
            System.out.println("同学"+id+"现在从大门出发");
            try {
                Thread.sleep((long) (Math.random()*10000));
                System.out.println("同学"+id+"到了自行车驿站开始等待");
                cyclicBarrier.await();
                System.out.println("同学"+id+"开始和另外两个人一起骑车");

            } catch (Exception e) {
              e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int num=3;
        CyclicBarrier cyclicBarrier=new CyclicBarrier(num, new Runnable() {
            @Override
            public void run() {
                System.out.println("三个人到了");
            }
        });
        for(int i=0;i<6;i++){
            new Thread(new Task(i+1,cyclicBarrier)).start();
        }
    }
}
